package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.meta.Column;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.vo.NursingLevelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.NursingLevelMapper;
import com.zzyl.nursing.domain.NursingLevel;
import com.zzyl.nursing.service.INursingLevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 护理等级Service业务层处理
 *
 * @author alexis
 * @date 2024-12-30
 */
@Slf4j
@Service
public class NursingLevelServiceImpl extends ServiceImpl<NursingLevelMapper, NursingLevel> implements INursingLevelService {
    @Autowired
    private NursingLevelMapper nursingLevelMapper;

    @Autowired
    private StringRedisTemplate redis;

    // 设置redis 的key前缀
    private static final String NURSING_LEVELS_PREFIX = "nursing:levels:";

    /*********
     *  使用Redis注意事项：
     *  ① 设计redis的key 一般用 : 连接 比如 模块:业务：具体内容  nursing:levels:all
     *  ② 使用缓存不能影响正常的业务逻辑 try ..... catch ......
     *  ③ 确定业务使用数据类型是什么？？  一般选择使用 string
     * @return List<NursingLevel>
     */

    @Override
    public List<NursingLevel> getAllLevels() {

        // 1. 首先需要查询缓存
        String redisKey = NURSING_LEVELS_PREFIX + "all";
        String jsonStr = null;
        List<NursingLevel> list = new ArrayList<NursingLevel>();
        try {
            jsonStr = redis.boundValueOps(redisKey).get();
            // 2.1 命中直接返回
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                list = JSONUtil.parseArray(jsonStr).toList(NursingLevel.class);
                if (CollUtil.isNotEmpty(list)) {
                    return list;
                }
            }
        } catch (Exception e) {
            log.error("操作缓存失败，失败的原因:{}", e.getMessage());
        }
        // 2.2 未命中 查询数据库，将数据缓存到redis，返回
        list = nursingLevelMapper.selectList(Wrappers.lambdaQuery(NursingLevel.class).eq(NursingLevel::getStatus, 1));
        try {
            String json = JSONUtil.toJsonStr(list);
            redis.boundValueOps(redisKey).set(json);
        } catch (Exception e) {
            log.error("写入缓存失败，失败的原因:{}", e.getMessage());
        }
        return list;
    }

    /**
     * 查询护理等级
     *
     * @param id 护理等级主键
     * @return 护理等级
     */
    @Override
    public NursingLevel selectNursingLevelById(Long id) {
        return nursingLevelMapper.selectById(id);
    }

    /**
     * 查询护理等级列表
     *
     * @param nursingLevel 护理等级
     * @return 护理等级
     */
    @Override
    public List<NursingLevel> selectNursingLevelList(NursingLevel nursingLevel) {
        return nursingLevelMapper.selectNursingLevelList(nursingLevel);
    }

    /**
     * 新增护理等级
     *
     * @param nursingLevel 护理等级
     * @return 结果
     */
    @Override
    public int insertNursingLevel(NursingLevel nursingLevel) {
        clearLevelCache(NURSING_LEVELS_PREFIX+"all");
        return nursingLevelMapper.insert(nursingLevel);
    }

    /**
     * 修改护理等级
     *
     * @param nursingLevel 护理等级
     * @return 结果
     */
    @Override
    public int updateNursingLevel(NursingLevel nursingLevel) {
        clearLevelCache(NURSING_LEVELS_PREFIX+"all");
        return nursingLevelMapper.updateById(nursingLevel);
    }

    /**
     * 批量删除护理等级
     *
     * @param ids 需要删除的护理等级主键
     * @return 结果
     */
    @Override
    public int deleteNursingLevelByIds(Long[] ids) {
        clearLevelCache(NURSING_LEVELS_PREFIX+"all");
        return nursingLevelMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除护理等级信息
     *
     * @param id 护理等级主键
     * @return 结果
     */
    @Override
    public int deleteNursingLevelById(Long id) {
        clearLevelCache(NURSING_LEVELS_PREFIX+"all");
        return nursingLevelMapper.deleteById(id);
    }

    /**
     * 查询护理等级Vo列表
     *
     * @param nursingLevel 条件
     * @return 结果
     */
    @Override
    public List<NursingLevelVo> selectNursingLevelVoList(NursingLevel nursingLevel) {
        return nursingLevelMapper.selectNursingLevelVoList(nursingLevel);
    }


    /**
     *  清空缓存
     * @param redisKey
     */
    private void clearLevelCache(String redisKey){
        try {
            redis.delete(redisKey);
        }catch (Exception e){
            log.error("清空缓存失败，失败的原因是:{}", e.getMessage());
        }
    }


}
